#!/bin/sh
#
# Copyright © 2019 – 2024 Red Hat, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#


collect()
(
    if $1; then
        postfix="_toolbox"
    else
        postfix=""
    fi

    manpages_list=""
    for dir in /usr/share/man/man*/ ; do
        for docs in $dir*; do
            package=$(rpm -qf $docs --qf "%{NAME}\n")
            if ! [[ $package = *"is not owned by any"* ]]; then
                manpages_list="$manpages_list$package\n"
            fi
        done
    done

    mkdir -p tmp
    echo -e "$manpages_list" | sort | uniq > tmp/docs_list$postfix
    rpm -qa --qf "%{NAME}\n" | sort | uniq > tmp/rpm_list$postfix
)


generate()
(
    diff -c tmp/rpm_list_toolbox tmp/rpm_list | grep -E "^\+" | tr -d '+ ' > tmp/missing_packages
    diff -c tmp/docs_list_toolbox tmp/docs_list | grep -E "^\+" | tr -d '+ ' > tmp/missing_manpages
    manpages_list=$(comm -1 -3 tmp/missing_packages tmp/missing_manpages)
    manpages_final=""
    while read -r line; do
        if [ "$(man $line)" != "" ]; then
            manpages_final="$manpages_final$line\n"
        fi
    done <<< "$manpages_list"
    echo -e "$manpages_final" >> missing-docs
)


case $1 in
    collect )
        shift
        toolbox=false
        case $1 in
            -t | --toolbox )
                toolbox=true
                ;;
        esac
        collect "$toolbox"
        exit
        ;;
    generate )
        generate
        exit
        ;;
    clean )
        rm -rf tmp
        exit
        ;;
    * )
        exit 1
esac
